/*
 * Copyright 2011 Clean GWT
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.cleangwt.json.client;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONValue;

/**
 * The {@link Collection} json deserializer.
 * 
 * @author Jess
 * @version 1.0
 * @since 1.0
 * 
 * @param <T> the type of item object
 */
public class CollectionDeserializer<T> extends JsonValueDeserializer<Collection<T>> {

  private static CollectionDeserializer<Object> impl;

  /**
   * @return the instance of gereric {@link Collection} deserializer
   */
  public static CollectionDeserializer<Object> get() {
    if (impl == null) {
      impl = new CollectionDeserializer<Object>(ObjectDeserializer.get());
    }
    return impl;
  }

  /**
   * Gets an instance with the given item deserializer.
   * 
   * @param itemDeserializer the item deserializer
   * @return the collection serializer of type
   */
  public static <T> CollectionDeserializer<T> get(JsonValueDeserializer<T> itemDeserializer) {
    return new CollectionDeserializer<T>(itemDeserializer);
  }

  private JsonValueDeserializer<T> itemDeserializer;

  private CollectionDeserializer(JsonValueDeserializer<T> itemDeserializer) {
    this.itemDeserializer = itemDeserializer;
  }

  @Override
  public Collection<T> fromJson(JSONValue jsonValue) {
    if (jsonValue == null || jsonValue.isNull() != null) {
      return null;
    }
    JSONArray jsonArray = jsonValue.isArray();
    List<T> list = new ArrayList<T>();
    for (int i = 0; i < jsonArray.size(); i++) {
      list.add(itemDeserializer.fromJson(jsonArray.get(i)));
    }
    return list;
  }

}
